#include "StdAfx.h"

void ADTTextureBlock::SetAlphaValues(ui32 cIndexX, ui32 cIndexY, ui8** alphaData, ui32 numLayers)
{
	if(numLayers > 4)
		throw std::out_of_range("numLayers > 4 in ADTTextureBlock::SetAlphaValue");

	ui32 chunkOfs = cIndexY * 16 + cIndexX;

	for(ui32 i = 0; i < numLayers; ++i)
		memcpy(m_alphaData[chunkOfs][i], alphaData[i], 4096);

	for(ui32 i = numLayers; i < 4; ++i)
		memset(m_alphaData[chunkOfs][i], 0, 4096);

}

void ADTTextureBlock::SetTextures(ui32 cIndexX, ui32 cIndexY, Texture** ppTextures, ui32 numTextures)
{
	if(numTextures > 4)
		throw std::out_of_range("numTextures > 4 in ADTTextureBlock::SetTextures");

	ui32 chunkOfs = cIndexY * 16 + cIndexX;

	for(ui32 i = 0; i < numTextures; ++i)
		m_textureBlocks[chunkOfs][i] = ppTextures[i];

	for(ui32 i = numTextures; i < 4; ++i)
		m_textureBlocks[chunkOfs][i] = NULL;
}

void ADTTextureBlock::InitTextureBlock()
{
	D3DXCreateTexture(sD3D, 256 * 16, 256 * 16, 9, 0, D3DFMT_DXT1, D3DPOOL_MANAGED, m_pColorTexture);
	IDirect3DSurface9* ppSurfaces[9];
	for(ui32 i = 0; i < 9; ++i)
		(*m_pColorTexture)->GetSurfaceLevel(i, ppSurfaces + i);

	ui8* surfaceData[9];
	for(ui32 i = 0; i < 9; ++i)
	{
		surfaceData[i] = new ui8[256 * (256 >> i) * (256 >> i) * 2];
		memset(surfaceData[i], 0x00, 256 * (256 >> i) * (256 >> i) * 2);
	}

	for(ui32 i = 0; i < 256; ++i)
	{
		Texture* pTexture = m_textureBlocks[i][0];
		IDirect3DTexture9* pNative = (*pTexture);
		if(pNative->GetLevelCount() >= 9)
		{
			for(ui32 j = 0; j < 9; ++j)
			{
				D3DSURFACE_DESC desc;
				D3DLOCKED_RECT dataRect;
				pNative->GetLevelDesc(j, &desc);
				pNative->LockRect(j, &dataRect, NULL, D3DLOCK_READONLY);
				ui32 rowWidth = 16 * desc.Width * 2;
				ui32 ofsX = i % 16;
				ui32 ofsY = i / 16;
				ui32 offsetX = ofsX * desc.Width * 2;
				ui32 offsetY = ofsY * rowWidth * desc.Height / 4;
				for(ui32 k = 0; k < desc.Height; ++k)
					memcpy(surfaceData[j] + offsetX + offsetY + k * rowWidth, (ui8*)dataRect.pBits + k * dataRect.Pitch, dataRect.Pitch);
				pNative->UnlockRect(j);
			}
		}
		else
			Log::Print("Shit...\n");
	}

	for(ui32 i = 0; i < 9; ++i)
	{
		RECT rect;
		rect.top = rect.left = 0;
		rect.right = rect.bottom = 16 * (256 >> i);
		D3DXLoadSurfaceFromMemory(ppSurfaces[i], NULL, NULL, surfaceData[i], D3DFMT_DXT1, 16 * 2 * (256 >> i), NULL, &rect, D3DX_DEFAULT, 0);
	}

	D3DXSaveSurfaceToFile("Surface.jpg", D3DXIFF_JPG, ppSurfaces[0], NULL, NULL);
	ExitThread(0);
}
